/* * @Author: shaohh // 多个文件批量上传 * @Date: 2022-10-13 13:44:31 * @Last
Modified by: shaohh * @Last Modified time: 2022-11-15 17:12:19 */
<template>
  <el-dialog
    title="上传文件"
    class="upload_dialog"
    v-if="dialogVisible"
    :visible.sync="dialogVisible"
    width="30%"
    :close-on-click-modal="false"
    :before-close="closeDialog"
    :show-close="false"
    v-hotkey="dialogSameHotkey"
    v-loading="loading"
    element-loading-background="rgba(0, 0, 0, 0.1)"
  >
    <div slot="title" class="upload_header">
      <span style="font-size: 16px">上传文件</span>
      <el-tooltip
        class="item"
        :disabled="!allUploadStatus"
        effect="light"
        content="文件上传中"
        placement="top"
      >
        <el-link :underline="false" @click="closeDialog"
          ><i class="el-icon-close"></i
        ></el-link>
      </el-tooltip>
    </div>
    <div class="item_box">
      <el-form
        v-if="showDate"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="巡查日期:" prop="date">
          <el-date-picker
            style="width: 100%"
            v-model="ruleForm.date"
            type="date"
            placeholder="请选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <el-upload
        class="upload-demo"
        drag
        ref="uploadFileRef"
        :action="apiAction"
        :headers="{ Accept: 'application/json', unionToken: token }"
        name="file"
        :accept="accept"
        :on-success="uploadSuccess"
        :on-error="uploadErr"
        :on-remove="removeFile"
        :on-change="changeFile"
        :before-upload="beforeAvatarUpload"
        :before-remove="beforeRemove"
        :limit="20"
        :file-list="showFileList"
        :on-exceed="handleExceed"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <slot name="uploadTip"></slot>
        </div>
        <!-- <div slot="file" slot-scope="{file}">
            <div style="display:flex;justify-content: space-between;align-items: center">
              <el-tooltip :content="file.name" placement="top" effect="light">
                <div>{{file.name+'-'+file.raw.uploading}}</div>
              </el-tooltip>
              <el-progress :stroke-width="3" :show-text="false" :percentage="file.percentage" v-show="true"></el-progress>
              <div v-show="!file.raw.uploading" ><i class="el-icon-close removeItem" @click="removeFile(file)"></i></div>
            </div>
          </div> -->
      </el-upload>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-tooltip
        class="item"
        :disabled="!allUploadStatus"
        effect="light"
        content="文件上传中"
        placement="top"
      >
        <el-button @click="closeDialog">取 消</el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        :disabled="!allUploadStatus"
        effect="light"
        content="文件上传中"
        placement="top"
      >
        <el-button type="primary" @click="addUploadFile">确 定</el-button>
      </el-tooltip>
    </span>
  </el-dialog>
</template>

<script>
// import throttle from 'lodash/throttle'
import throttle from "lodash/debounce";
import { minioDeleteFile } from "@/api/upload.js";
import dayjs from "dayjs";
export default {
  components: {},
  data() {
    return {
      apiAction: "",
      loading: false,
      dialogVisible: false,
      token: localStorage.getItem("unionToken"),
      cb: null,
      fileList: [],
      uploadState: false,
      ruleForm: {
        date: "",
      },
      rules: {
        date: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
      },
      uploadList: [], // 已经上传的文件列表 显示的
      UpLoadFilesLength: 0, //文件上传个数
      allUploadStatus: false,
      dialogSameHotkey: {
        delete: this.deleteKey,
      },
      showFileList: [],
    };
  },
  mounted() {
    let config = require("@/config/env." + process.env.NODE_ENV);
    this.apiAction =
      config.baseApi + "lab-bimpack/minioManage/minioUploadMultipleFile";
  },
  props: {
    typeId: {
      // 必传
      // type:String,
      // default:()=>''
      require: true,
    },
    showDate: {
      type: Boolean,
      default: () => false,
    },
    typeName: {
      type: String,
      default: () => "",
    },
    api: {
      type: Function,
      require: true,
    },
    accept: {
      type: String,
      default: () => ".jpg,.png,.pdf,.docx,.doc,.xlsx,.xls,.ppt,.pptx",
    },
  },
  computed: {},
  methods: {
    deleteKey() {
      return;
    },
    changeFile(file, fileList) {
      // console.log(fileList,'niuda')
    },
    handleExceed(files, fileList) {
      this.$message.error(`文件上传数量超过限制`);
    },
    // 文件上传的限制
    beforeAvatarUpload(file) {
      if (file.name.length > 100) {
        this.$message.error(file.name + "文件名称长度超出限制");
        return false;
      }

      file.uploading = false;
      const isLt2M = file.size / 1024 / 1024 < 20;
      // const isLt1M = file.size / 1024 / 1024 > 1;
      let fileSuffix = file.name
        .substring(file.name.lastIndexOf("."))
        .toLowerCase();
      let errMessage = [];
      if (this.accept.indexOf(fileSuffix) < 0) {
        errMessage.push(`${file.name} 文件格式不符合`);
      } else if (!isLt2M) {
        errMessage.push(`${file.name} 文件大小超出限制`); //不能超过20MB
      }
      // else if ((fileSuffix == ".xls" || fileSuffix == ".xlsx") && isLt1M) {
      //   errMessage.push(`excel文件最大不能超过1M`);
      // }
      if (errMessage.length > 0) {
        setTimeout(() => {
          this.$sysUtil.showErr({ message: errMessage });
        }, 0);
      } else {
        this.uploadState = true;
        file.uploading = true;

        this.allUploadStatus = true;
      }
      // if (isLt2M && this.accept.indexOf(fileSuffix) > -1) {

      // }

      return errMessage.length == 0;
    },
    // 关闭弹窗的回调
    closeDialog() {
      if (this.allUploadStatus) {
        return;
      }
      this.dialogVisible = false;
      this.$refs.uploadFileRef.clearFiles();
      this.deleteFile(this.fileList);
    },
    uploadErr() {
      this.$message.error("上传失败");
      this.allUploadStatus = false;
    },
    // 调用接口删除
    deleteFile(arr) {
      if (arr.length == 1) {
        this.UpLoadFilesLength--;
      }
      let data = arr.map((item) => item.deleteAddress);
      if (data.length == 0) return;
      minioDeleteFile({ fileNames: data })
        .then((res) => {
          console.log("删除成功");
        })
        .catch();
    },

    addUploadFile: throttle(
      function () {
        if (this.allUploadStatus) {
          // 文件上传中
          return;
        }
        if (this.showDate) {
          this.$refs.ruleForm.validate((valid) => {
            if (!valid) {
              return false;
            } else {
              // let data = this.fileList.map(item=>{
              //   return {...item,...{date:dayjs(this.ruleForm.date).format('YYYY-MM-DD')}}
              // })
              // console.log(data)
              // addYingji(data).then(res=>{
              //   this.$message.success('上传成功')
              // }).catch()
              this.uploadFileToApi(this.ruleForm.date);
            }
          });
        } else {
          this.uploadFileToApi();
        }
      },
      1000,
      { leading: true, trailing: false }
    ),
    // addUploadFile(){

    // },
    uploadFileToApi(date) {
      if (this.fileList.length < 1) {
        this.$message.error("请上传至少一个文件");
        return;
      }

      let countSize = 0;
      this.fileList.forEach((item) => {
        countSize += item.size;
      });
      // if(countSize/1024/1024>180){
      //   this.$message.error('总文件大小超出限制')//上传总文件大小不能超过 180MB!
      //   return
      // }
      let data = JSON.parse(JSON.stringify(this.fileList));
      data.forEach((item) => {
        item.typeId = this.typeId;
        item.typeName = this.typeName;
      });
      if (date) {
        data.forEach((item) => {
          item.date = dayjs(date).format("YYYY-MM-DD");
        });
      }
      console.log(data);
      this.loading = true;
      this.api({ list: data })
        .then((res) => {
          this.dialogVisible = false;
          this.$message.success("上传成功");
          if (typeof this.cb === "function") {
            this.cb();
          }
        })
        .catch()
        .finally(() => {
          this.loading = false;
        });
    },
    beforeRemove() {
      if (window.event.type == "keydown") {
        return false;
      }
      return true;
    },

    removeFile(file) {
      this.fileList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.fileList.splice(index, 1);
          this.deleteFile([item]);
        }
      });
      this.uploadList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.uploadList.splice(index, 1);
        }
      });
    },
    uploadSuccess(res, file) {
      res.data = res.data[0];
      if (this.$refs.uploadFileRef.uploadFiles) {
        let length = this.$refs.uploadFileRef.uploadFiles.length;
        this.UpLoadFilesLength++;
        if (this.UpLoadFilesLength == length) {
          this.allUploadStatus = false;
        }
      }
      file.raw.uploading = false;
      this.uploadState = false;
      this.fileList.push({
        address: res.data.url,
        name: file.name,
        previewAddress: res.data.previewUrl,
        size: file.size,
        uid: file.uid,
        deleteAddress: res.data.nameByDel,
      });
      if (!this.dialogVisible) {
        this.deleteFile(this.fileList);
      }
      this.uploadList.push(file);
    },
    openDialog(cb) {
      this.UpLoadFilesLength = 0;
      this.cb = cb;
      this.dialogVisible = true;
      this.fileList = [];
      this.ruleForm = {
        date: "",
      };
    },
  },
};
</script>

<style lang="less" scoped>
.removeItem:hover {
  color: #38c6da;
}
.removeItem {
  cursor: pointer;
}
.upload-demo {
  /deep/ .el-upload-list__item-name {
    cursor: default !important;
  }
  /deep/ .is-uploading {
    .el-icon-close {
      display: none;
    }
  }
  /deep/ .el-upload-list {
    max-height: 310px;
    overflow: auto;
  }
}
.upload-demo {
  // text-align: center;
  width: 75%;
  margin: 0 auto;
  /deep/.el-upload {
    width: 100%;
  }
  /deep/ .el-upload-dragger {
    width: 100%;
  }
  /deep/ .el-icon-close {
    display: block;
  }
  /deep/ .el-icon-upload-success {
    display: none;
  }
}
.showItem {
  /deep/ .el-upload-list {
    display: block !important;
  }
}
.showItem /deep/ .el-upload-list {
  display: block !important;
}

.showItem {
  /deep/ .el-upload {
    display: none;
  }
}
.upload_header {
  display: flex;
  justify-content: space-between;
  margin-left: 20px;
  margin-right: 20px;
}
.upload_dialog {
  // /deep/ .el-dialog__title{

  // }
  /deep/ .el-dialog__header {
    padding-left: 0;
    padding-right: 0;
    border-bottom: 1px solid #dcdfe6;
    // margin :0 20px;
  }
}
.upload_dialog {
  /deep/ .el-dialog__body {
    padding-top: 12px;
  }
}
.desc_item {
  margin-top: 12px;
  text-align: center;
  line-height: 46px;
}
</style>
